cmake_minimum_required(VERSION 3.10)

project(Template)

file(GLOB SRCS
    ${PROJECT_SOURCE_DIR}/app/*.cpp
    ${PROJECT_SOURCE_DIR}/system/*.cpp
    ${PROJECT_SOURCE_DIR}/system/drivers/gpio/*.cpp
    ${PROJECT_SOURCE_DIR}/system/drivers/usart/*.cpp
)

include_directories(
    ${PROJECT_SOURCE_DIR}/app
    ${PROJECT_SOURCE_DIR}/system
    ${PROJECT_SOURCE_DIR}/system/drivers
)

set(CMAKE_MODULE_PATH
    ${PROJECT_SOURCE_DIR}/system/camellia
)

find_package(Camellia)

include_directories(
    ${Camellia_INCLUDE_DIRS}
)

set(STARTUP_FILE ${PROJECT_SOURCE_DIR}/startup.s)
set(LINKER_SCRIPT ${PROJECT_SOURCE_DIR}/link.ld)
set(LIBS_FLAG "-lc -lstdc++ -lnosys -lm")

enable_language(ASM)

set(CMAKE_C_COMPILER arm-none-eabi-gcc)
set(CMAKE_CXX_COMPILER arm-none-eabi-g++)
set(CMAKE_ASM_COMPILER arm-none-eabi-gcc)
set(CMAKE_OBJCOPY arm-none-eabi-objcopy)
set(CMAKE_SIZE arm-none-eabi-size)

set(MCU_FLAGS "-mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard")

set(CMAKE_ASM_FLAGS "-x assembler-with-cpp ${MCU_FLAGS} -g -Og -Wall -fdata-sections -ffunction-sections -MMD")
set(CMAKE_C_FLAGS "${MCU_FLAGS} -g -Og -Wall -fdata-sections -ffunction-sections -MMD")
set(CMAKE_CXX_FLAGS "${MCU_FLAGS} -g -Og -Wall -fdata-sections -ffunction-sections -MMD")

set(CMAKE_EXE_LINKER_FLAGS "${MCU_FLAGS} -g -Og -specs=nano.specs -specs=nosys.specs -T ${LINKER_SCRIPT} ${LIBS_FLAG} -Wl,-Map=${PROJECT_BINARY_DIR}/${PROJECT_NAME}.map,--cref -Wl,--gc-sections")

add_executable(${PROJECT_NAME}.elf ${STARTUP_FILE} ${SRCS})

target_link_libraries(${PROJECT_NAME}.elf Camellia)

add_custom_command(TARGET "${PROJECT_NAME}.elf" POST_BUILD
COMMAND ${CMAKE_OBJCOPY} -Obinary ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.elf ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.bin
COMMAND ${CMAKE_OBJCOPY} -Oihex ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.elf ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.hex
COMMENT "Building binary file and hex file"
COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.bin "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.bin"
COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.hex "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.hex"
COMMAND ${CMAKE_SIZE} --format=berkeley ${PROJECT_NAME}.elf ${PROJECT_NAME}.hex
COMMENT "Invoking: Cross Arm GNU Print Size"
)